﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web;
using Hammock.Authentication.Basic;
using Hammock;

namespace TwilioSharp.Code.Twilio  
{
    public class TwilioApi
    {
        private readonly string _accountSid;
        private readonly string _accountToken;
        private readonly string _outboundNumber;
        private const string TwilioApiUrl = "https://api.twilio.com";
        private const string TwilioApiVersion = "2008-08-01";
         

        public string AccountGuid
        {
            get
            {
                return _accountSid;
            }
        }
        
        public TwilioApi(string accountSid, string accountToken,string outboundNumber)
        {
            _accountSid = accountSid;
            _accountToken = accountToken;
            _outboundNumber = outboundNumber;
        }
        public TwilioApi()
        {
            _accountSid = ConfigurationManager.AppSettings["Twilio.AccountSid"];
            _accountToken = ConfigurationManager.AppSettings["Twilio.AuthToken"];
            _outboundNumber = ConfigurationManager.AppSettings["Twilio.OutboundNumber"];
        }

        public void PlaceCall(string called, Uri url)
        {
            Trace.Write("Begin Request", "Twilio.PlaceCall");

            var client = new RestClient()
            {
                Authority = TwilioApiUrl
                
            };
            var request = new RestRequest()
            {
                VersionPath = TwilioApiVersion,
                Path = "Accounts/" + _accountSid + "/Calls",
                Credentials = new BasicAuthCredentials(){Username = _accountSid, Password = _accountToken}
            };

            request.AddField("Caller", _outboundNumber);
            request.AddField("Called", called);
            request.AddField("Url", url.ToString());

            var response = client.Request(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                Trace.TraceWarning(response.Content);
            }

            Trace.Write("End Request", "Twilio.PlaceCall");
        }
    }
}